package com.example.demo.mqserver;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张
 * Date: 2024-08-22
 * Time: 16:51
 */

import com.example.demo.common.*;
import com.example.demo.mqserver.core.BasicProperties;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 这个类就是消息队列的本体服务器
 * 本质上就是一个TCP的服务器
 */
public class BrokerServer {
    private ServerSocket serverSocket = null;

    //当前考虑一个BrokerServer只有一个虚拟主机
    private VirtualHost virtualHost = new VirtualHost("default");
    //使用这个哈希表,标识当前所有的会话(也就是说当前有哪些客户端正在和我们服务器进行通信)
    //此处的key为channelId
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<String,Socket>();
    //以引入线程池来处理多个客户端的请求
    private ExecutorService executorService = null;
    //引入一个Boolean变量来控制服务器是否继续运行
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void  start() throws IOException {
        System.out.println("[BrokerServer] 启动!!");
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                Socket clientSocket = serverSocket.accept();//获取客户端连接
                //把处理连接的任务丢给线程池来处理
                executorService.submit(() -> {
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器停止运行!!");
        }
    }

    //一般来说停止服务器,就是直接kill掉对应进程就行了
    //此处还是搞一个停止方法(给后续的单元测试搞简单点)
    public void stop() throws IOException {
        runnable = false;//循环给停止
        //把线程池中的任务都放弃了,让线程都销毁
        executorService.shutdown();
        serverSocket.close();
    }

    //通过这个方法,来处理一个客户端的连接
    //在这一个连接中,可能会涉及到多个请求和响应
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            // 这里需要特定格式来读取并解析,此时就需要DataInputStream 和 DataOutputStream
            try(DataInputStream dataInputStream = new DataInputStream(inputStream);
                DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    //1.读取请求并解析
                    Request request = readRequest(dataInputStream);
                    //2.根据请求计算响应
                    Response response = process(request,clientSocket);
                    //3.把响应写回给客户端
                    writeResponse(dataOutputStream,response);
                }
            }
        } catch (EOFException | SocketException e) {
            // 对于DataInputStream来说 如果说读到EOF就代表请求的数据全都读取完毕了 会抛出一个EOFException异常
            // 需要借助这个异常来结束循环
            System.out.println("[BrokerServer] connection 关闭! 客户端地址 : " + clientSocket.getInetAddress().toString()
                    + ":" + clientSocket.getPort());
        } catch (IOException  | ClassNotFoundException | MqException e) {
            System.out.println("[BrokerServer] connection 出现异常 !!");
            e.printStackTrace();
        } finally {
            try {
                //当连接处理完了就需要关闭对应的Socket对象
                clientSocket.close();
                //一个TCP连接中,可能包含多个Channel, 需要把当前这个Socket对应的所有的channel也顺便清理了
                //把这个清理键值对的方法放到finally主要是防一首对面的TCP连接突然断开,此时session中的键值对也要确认能够被清除
                clearCloseSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //解析Request
    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if(n != request.getLength()) {
            throw new IOException("读取请求格式出错!!");
        }
        request.setPayload(payload);
        return request;
    }

    //把响应给写回到客户端
    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        //保证当前写的数据能够快速进入网卡里,而不是卡在内存中
        dataOutputStream.flush();
    }

    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        // 1.把request中的payload 做一个初步的解析
        // 当前请求中的payload,里面放的内容是根据Type来走的,每个Type都有对应的参数类,
        //但是它们都有一个公共的父类
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        //打印日志
        System.out.println("[Request] rid = " + basicArguments.getRid() + " ,channelId = " + basicArguments.getChannelId() +
                ", type = " + request.getType() + " , length = " + request.getLength());
        //2.根据Type的值来进一步区分这次请求要干啥
        boolean ok = true;
        if(request.getType() == 0x1) {
            //创建一个Channel
            sessions.put(basicArguments.getChannelId(),clientSocket);
            System.out.println("[BrokerServer] 创建Channel完成!!! channelId = " + basicArguments.getChannelId());
        } else if(request.getType() == 0x2) {
            //销毁Channel
            sessions.remove(basicArguments.getChannelId());
            System.out.println("[BrokerServer] 成功销毁Channel!!! channelId = " + basicArguments.getChannelId());
        } else if(request.getType() == 0x3) {
            //创建一个交换机,此时payload就是ExchangeDeclareArguments对象
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            //调用virtualHost
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(),arguments.getExchangeType(),arguments.isDurable(),
                    arguments.isAutoDelete(),arguments.getArguments());
            System.out.println("[BrokerServer] 创建交换机完成!! exchangeName = " + arguments.getExchangeName());
        } else if(request.getType() == 0x4) {
            //删除一个交换机
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
            System.out.println("[BrokerServer] 删除交换机成功!! exchangeName = " + arguments.getExchangeName());
        } else if(request.getType() == 0x5) {
            //创建一个队列
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(),arguments.isDurable(),arguments.isExclusive(),
                    arguments.isAutoDelete(),arguments.getArguments());
            System.out.println("[BrokerServer] 创建队列成功!! queueName = " + arguments.getQueueName());
        } else if(request.getType() == 0x6) {
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());
            System.out.println("[BrokerServer] 删除队列成功!! queueName = " + arguments.getQueueName());
        } else if(request.getType() == 0x7) {
            //创建绑定
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(),arguments.getExchangeName(),arguments.getBindingKey());
            System.out.println("[BrokerServer] 创建绑定成功!! queueName = " + arguments.getQueueName() + ", exchangeName = " + arguments.getExchangeName());
        } else if(request.getType() == 0x8) {
            QueueUnbindArguments arguments = (QueueUnbindArguments) basicArguments;
            ok = virtualHost.queueUnBind(arguments.getQueueName(),arguments.getExchangeName());
            System.out.println("[BrokerServer] 解除绑定成功!! queueName = " + arguments.getQueueName() + ", exchangeName = " + arguments.getExchangeName());
        } else if(request.getType() == 0x9) {
            //发送消息
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublic(arguments.getExchangeName(),arguments.getRoutingKey(),
                    arguments.getBasicProperties(),arguments.getBoyd());
         } else if(request.getType() == 0xa) {
            //订阅消息 -- 在服务器端的回调函数写一个固定的
            BasicConsumeArguments arguments = (BasicConsumeArguments)  basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(), new Consumer() {
                //这个回调函数要做的就是,把在服务器收到的消息回传给对应客户端(消费者端)
                @Override
                public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                    //先知道当前这个收到的消息要发给谁
                    //此处的consumerTag 其实是一个channelId,根据channelId去session中进行查询,就可以得到对应的Socket
                    //往得到的Socket对象发送消息即可
                    //1.根据consumerTag(channelId找到对应的socket对象)
                    Socket socket = sessions.get(consumerTag);
                    if(socket == null || socket.isClosed()) {
                        throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭!!");
                    }
                    //2.构造响应数据
                    //此处response的payload就是一个SubScribeReturns
                    //SubScribeReturns是只有响应没有请求的,这个时候的rid就失去原本的作用了,rid是为了响应和请求对上的
                    //此处的rid不进行set也是可以的
                    SubScribeReturns subScribeReturns = new SubScribeReturns();
                    subScribeReturns.setChannelId(consumerTag);
                    subScribeReturns.setOk(true);
                    subScribeReturns.setBasicProperties(basicProperties);
                    subScribeReturns.setBody(body);
                    byte[] payload = BinaryTool.toBytes(subScribeReturns);
                    //0xc标识服务器给消费者客户端推送消息数据
                    Response response = new Response();
                    response.setType(0xc);
                    response.setLength(payload.length);
                    response.setPayload(payload);
                    //3.把响应写回给客户端
                    // 注:此处的dataOutputStream 不能进行close!!!
                    //    如果 此处把dataOutStream给关闭了,就会直接把socket里面的outPutStream给关了
                    //    此时就无法继续往socket中写入后续的数据了
                    DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                    writeResponse(dataOutputStream,response);
                }
            });
         } else if (request.getType() == 0xb) {
            //调用BasicAck 来进行确认消息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(),arguments.getMessageId());
        } else {
            //当前的type是非法的
            throw new MqException("[BrokerServer] 未知type !! type = " + request.getType());
        }
        //3.构造响应
        BasicReturn basicReturn = new BasicReturn();
        basicReturn.setRid(basicArguments.getRid());
        basicReturn.setChannelId(basicArguments.getChannelId());
        basicReturn.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturn);

        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response] rid = " + basicArguments.getRid() + ", channelId = " + basicArguments.getChannelId() +
                ",type = " + response.getType() + ",length = " + response.getLength());
        return response;
    }

    private void clearCloseSession(Socket clientSocket) {
        //此处要做的事情,就是变量上述的session Hash表,把被关闭的Socket键值对给删掉
        //遍历hash
        List<String> toDeleteChannelId = new ArrayList<>();
        for (Map.Entry<String,Socket> entry : sessions.entrySet()) {
            if(entry.getValue() == clientSocket) {
                //不能在这里 进行删除(不要在集合类中一般遍历一边删除)
                //一边遍历一边删除可能会导致迭代器失效的问题
                toDeleteChannelId.add(entry.getKey());
            }
        }

        for (String s : toDeleteChannelId) {
            sessions.remove(s);
        }

        System.out.println("[BrokerServer] 清理session完成!! 被清理的channelId = " + toDeleteChannelId);
    }
}
